(function () {
    angular.module('app')
        .component('xxShoppingCart',{
            templateUrl:'./app/user/shopping-cart/shopping-cart.html',
            controller:ctrl
        });

    function ctrl($scope,$state,userService,ShoppingCartFactory) {
        $scope.drugInCart = [];
        $scope.selectedDrug = [];
        $scope.totalPrice = 0.00;
        $scope.userId = userService.user['userId'];

        function getDrugInCart(){
            function cb(err, res) {
                console.log(err,res);
                if(!err) {
                    $scope.drugInCart = res;
                    console.log(err,res);
                }
            }
            ShoppingCartFactory.getDrugInCart($scope.userId, cb);
        }
        getDrugInCart();

        function totalPrice(selectedDrug) {
            if (selectedDrug.length===0) {
                $scope.totalPrice = 0.00;
            }
            else {
                var sum = 0;
                for (var i=0; i<selectedDrug.length; i++) {
                    sum += selectedDrug[i]['price'] * selectedDrug[i]['number'];
                }
                $scope.totalPrice = sum;
            }
        }

        $scope.drugInfo = function (drugId) {
            $state.go('user.drug-info',{drugId:drugId});
        };

        $scope.exists = function (item, list) {
            return list.indexOf(item) > -1;
        };
        $scope.toggle = function (item, list) {
            var idx = list.indexOf(item);
            if (idx > -1) {
                list.splice(idx, 1);
            }
            else {
                list.push(item);
            }
            totalPrice($scope.selectedDrug);
        };

        $scope.isIndeterminate = function() {
            return ($scope.selectedDrug.length !== 0 &&
                $scope.selectedDrug.length !== $scope.drugInCart.length);
        };
        $scope.isCheckedAll = function() {
            return $scope.selectedDrug.length === $scope.drugInCart.length;
        };
        $scope.toggleAll = function() {
            if ($scope.selectedDrug.length === $scope.drugInCart.length) {
                $scope.selectedDrug = [];
            } else if ($scope.selectedDrug.length === 0 || $scope.selectedDrug.length > 0) {
                $scope.selectedDrug = $scope.drugInCart.slice(0);
            }
            totalPrice($scope.selectedDrug);
        };


        //totalPrice($scope.selectedDrug);
        //console.log($scope.totalPrice);

    }
})();
